<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter"
      :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="合同名称" prop="conName">
              <el-input v-model="queryParams.conName" placeholder="请输入合同名称" clearable style="width: 240px" />
            </el-form-item>
            <el-form-item label="执行总裁" prop="proPresidentId">
              <el-select
                :model-value="selectedSearchPresident ? selectedSearchPresident.userName || selectedSearchPresident.nickName : ''"
                placeholder="请选择执行总裁" style="width: 240px" clearable @click="showSearchPresidentSelector = true"
                @clear="clearSearchPresident">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchPresidentSelector = true"> 选择执行总裁 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>
            <el-form-item label="负责人" prop="proLeaderId">
              <el-select
                :model-value="selectedSearchLeader ? selectedSearchLeader.userName || selectedSearchLeader.nickName : ''"
                placeholder="请选择项目负责人" style="width: 240px" clearable @click="showSearchLeaderSelector = true"
                @clear="clearSearchLeader">
                <template #empty>
                  <div style="text-align: center; padding: 10px">
                    <el-button type="primary" plain @click="showSearchLeaderSelector = true"> 选择项目负责人 </el-button>
                  </div>
                </template>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd"
              v-hasPermi="['project:receiveRegister:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()"
              v-hasPermi="['project:receiveRegister:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()"
              v-hasPermi="['project:receiveRegister:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport"
              v-hasPermi="['project:receiveRegister:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="proReceiveRegisterList" @selection-change="handleSelectionChange" border>
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="主键" align="center" prop="id" v-if="false" />
        <el-table-column label="登记人" align="center" prop="registerName" width="150" />
        <el-table-column label="登记时间" align="center" prop="registerTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.registerTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同名称" align="center" prop="conName" :show-overflow-tooltip="true" />
        <el-table-column label="收款日期" align="center" prop="receiveTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.receiveTime, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="收款金额" align="center" prop="receiveAmount" />
        <el-table-column label="收款负责人" align="center" prop="proReceivedName" :show-overflow-tooltip="true" />

        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['project:receiveRegister:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['project:receiveRegister:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改回款登记对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="900px" append-to-body>
      <el-form ref="proReceiveRegisterFormRef" :model="form" :rules="rules" label-width="130px" label-position="left"
        hide-required-asterisk>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item prop="registerBy" :required="true">
              <template #label><span class="asterisk">*</span>回款登记人</template>
              <el-input :value="form.registerName || userStore.name" readonly style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="registerTime" :required="true">
              <template #label><span class="asterisk">*</span>登记时间</template>
              <el-date-picker clearable v-model="form.registerTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择登记时间" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="conId" :required="true">
              <template #label><span class="asterisk">*</span>合同名称</template>
              <el-select v-model="form.conId" placeholder="请输入合同名称搜索" clearable filterable remote reserve-keyword
                :remote-method="searchContracts" :loading="contractLoading" style="width: 100%"
                @change="handleContractChange" @visible-change="handleContractVisibleChange">
                <el-option v-for="contract in contractList" :key="contract.id"
                  :label="`${contract.contractName} (${contract.contractNumber || ''})`" :value="contract.id" />
                <template #empty>
                  <div class="text-center p-2">
                    <span v-if="contractSearchKeyword && contractList.length === 0"> 未找到相关合同 </span>
                    <span v-else> 请输入合同名称进行搜索 </span>
                  </div>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <template #label>合同收款负责人</template>
              <el-input :value="contractReceiveLeaders || '暂无收款负责人'" readonly style="width: 100%"
                :class="{ 'readonly-placeholder': !contractReceiveLeaders }" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <template #label>项目负责人</template>
              <el-input :value="contractLeadersName || '暂无项目负责人'" readonly style="width: 100%"
                :class="{ 'readonly-placeholder': !contractLeadersName }" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item>
              <template #label>项目执行总裁</template>
              <el-input :value="contractPresidentsName || '暂无执行总裁'" readonly style="width: 100%"
                :class="{ 'readonly-placeholder': !contractPresidentsName }" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="receiveAmount" :required="true">
              <template #label><span class="asterisk">*</span>收款金额</template>
              <el-input v-model="form.receiveAmount" placeholder="请输入收款金额（保留两位小数）" style="width: 100%"
                @input="handleReceiveAmountInput">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item prop="receiveTime" :required="true">
              <template #label><span class="asterisk">*</span>收款日期</template>
              <el-date-picker clearable v-model="form.receiveTime" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择收款日期" style="width: 100%" />
            </el-form-item>
          </el-col>


          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入内容" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 搜索条件用的执行总裁选择器 -->
    <UserSelector v-model:visible="showSearchPresidentSelector" title="选择执行总裁"
      :selected-user-ids="queryParams?.proPresidentId" :selected-user-names="selectedSearchPresidentName"
      :multiple="false" @confirmWithIds="handleSearchPresidentConfirm" @cancel="handleSearchPresidentCancel" />

    <!-- 搜索条件用的项目负责人选择器 -->
    <UserSelector v-model:visible="showSearchLeaderSelector" title="选择项目负责人"
      :selected-user-ids="queryParams?.proLeaderId" :selected-user-names="selectedSearchLeaderName" :multiple="false"
      @confirmWithIds="handleSearchLeaderConfirm" @cancel="handleSearchLeaderCancel" />


  </div>
</template>

<script setup name="ProReceiveRegister" lang="ts">
import {
  listProReceiveRegister,
  getProReceiveRegister,
  delProReceiveRegister,
  addProReceiveRegister,
  updateProReceiveRegister
} from '@/api/project/receive';
import { ProReceiveRegisterVO, ProReceiveRegisterForm } from '@/api/project/receive/types';

import { useUserStore } from '@/store/modules/user';
import { listProContract, getProContract, getReceiveLeadersByContractId } from '@/api/project/init/contract';
import { ProContractVO } from '@/api/project/init/contract/types';

import request from '@/utils/request';
import { getToday } from '@/utils/dateUtils';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const proReceiveRegisterList = ref<ProReceiveRegisterVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const proReceiveRegisterFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// 搜索条件用户选择相关
const showSearchPresidentSelector = ref(false);
const selectedSearchPresident = ref(null);
const selectedSearchPresidentName = ref('');

const showSearchLeaderSelector = ref(false);
const selectedSearchLeader = ref(null);
const selectedSearchLeaderName = ref('');



const contractList = ref<ProContractVO[]>([]);
const contractLoading = ref(false);
const contractSearchKeyword = ref('');
const contractReceiveLeaders = ref<string>('');
const contractLeadersName = ref<string>('');
const contractPresidentsName = ref<string>('');

const searchContracts = (query: string) => {
  contractSearchKeyword.value = query;
  if (searchContracts.timer) clearTimeout(searchContracts.timer);
  searchContracts.timer = setTimeout(() => {
    // 如果搜索关键词为空，也获取合同列表（显示所有符合条件的合同）
    getContractList(query);
  }, 300);
};
searchContracts.timer = null;

const getContractList = async (searchKeyword = '') => {
  try {
    contractLoading.value = true;
    const res = await listProContract({
      pageNum: 1,
      pageSize: 50,
      contractName: searchKeyword || undefined,
      proStatus: '3'
    });
    // 参考审查记录页面的处理方式，响应拦截器处理后直接使用res.rows
    contractList.value = res.rows || [];
    console.log('合同列表数据:', contractList.value);
  } catch (error) {
    console.error('获取合同列表失败:', error);
    contractList.value = [];
  } finally {
    contractLoading.value = false;
  }
};

const handleContractVisibleChange = (visible: boolean) => {
  if (visible && contractList.value.length === 0) {
    getContractList();
  }
};

const handleContractChange = async (contractId: string | number) => {
  if (!contractId) {
    // 清空收款负责人信息
    contractReceiveLeaders.value = '';
    return;
  }

  // 获取选中的合同信息
  const contract = contractList.value.find((c) => c.id === contractId);
  if (contract) {
    // 设置项目负责人和执行总裁信息
    contractLeadersName.value = contract.leadersName || '';
    contractPresidentsName.value = contract.presidentsName || '';

    // 通过合同ID获取收款负责人信息
    try {
      const receiveLeadersRes = await getReceiveLeadersByContractId(contractId);
      const receiveLeaders = receiveLeadersRes.data;
      if (receiveLeaders && receiveLeaders.trim()) {
        contractReceiveLeaders.value = receiveLeaders;
      } else {
        contractReceiveLeaders.value = '';
      }
    } catch (error) {
      contractReceiveLeaders.value = '';
      console.error('获取合同收款负责人信息失败:', error);
    }
  }
};

const userStore = useUserStore();

const initFormData: ProReceiveRegisterForm & {
  registerName?: string;
  receiveAmount?: string | number;
  conId?: string | number;
} = {
  id: undefined,
  registerTime: undefined,
  registerBy: undefined,
  conId: undefined,
  receiveTime: undefined,
  receiveAmount: undefined,
  registerName: '',
  remark: undefined
};

const data = reactive<
  PageData<
    ProReceiveRegisterForm & {
      registerName?: string;
      receiveAmount?: string | number;
    },
    any
  >
>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    conName: undefined,
    proPresidentId: undefined,
    proLeaderId: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    registerTime: [{ required: true, message: '登记时间不能为空', trigger: 'change' }],
    registerBy: [{ required: true, message: '登记人不能为空', trigger: 'blur' }],
    contractId: [{ required: true, message: '合同名称不能为空', trigger: 'change' }],
    receiveTime: [{ required: true, message: '收款日期不能为空', trigger: 'change' }],
    receiveAmount: [
      { required: true, message: '收款金额不能为空', trigger: 'blur' },
      { pattern: /^\d+(\.\d{1,2})?$/, message: '请输入正确的金额格式（最多两位小数）', trigger: 'blur' }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 处理搜索条件执行总裁选择确认
const handleSearchPresidentConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchPresident.value = data.users[0];
    selectedSearchPresidentName.value = data.userNames || '';

    if (queryParams.value) {
      queryParams.value.proPresidentId = data.userIds || '';
    }
  } else {
    selectedSearchPresident.value = null;
    selectedSearchPresidentName.value = '';
    if (queryParams.value) {
      queryParams.value.proPresidentId = '';
    }
  }

  showSearchPresidentSelector.value = false;
};

// 取消搜索条件执行总裁选择
const handleSearchPresidentCancel = () => {
  showSearchPresidentSelector.value = false;
};

// 清空搜索条件执行总裁选择
const clearSearchPresident = () => {
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  if (queryParams.value) {
    queryParams.value.proPresidentsId = '';
  }
};

// 处理搜索条件项目负责人选择确认
const handleSearchLeaderConfirm = (data) => {
  if (data.users && data.users.length > 0) {
    selectedSearchLeader.value = data.users[0];
    selectedSearchLeaderName.value = data.userNames || '';

    if (queryParams.value) {
      queryParams.value.proLeaderId = data.userIds || '';
    }
  } else {
    selectedSearchLeader.value = null;
    selectedSearchLeaderName.value = '';
    if (queryParams.value) {
      queryParams.value.proLeaderId = '';
    }
  }

  showSearchLeaderSelector.value = false;
};

// 取消搜索条件项目负责人选择
const handleSearchLeaderCancel = () => {
  showSearchLeaderSelector.value = false;
};

// 清空搜索条件项目负责人选择
const clearSearchLeader = () => {
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';
  if (queryParams.value) {
    queryParams.value.proLeadersId = '';
  }
};



// 处理收款金额输入格式化
const handleReceiveAmountInput = (value: string) => {
  if (!value) return;

  // 只允许数字和小数点
  let formattedValue = value.replace(/[^\d.]/g, '');

  // 确保只有一个小数点
  const parts = formattedValue.split('.');
  if (parts.length > 2) {
    formattedValue = parts[0] + '.' + parts.slice(1).join('');
  }

  // 限制小数点后最多两位
  if (parts.length === 2 && parts[1].length > 2) {
    formattedValue = parts[0] + '.' + parts[1].substring(0, 2);
  }

  // 更新表单值
  if (form.value) {
    (form.value as any).receiveAmount = formattedValue;
  }
};

/** 查询回款登记列表 */
const getList = async () => {
  loading.value = true;
  const res = await listProReceiveRegister(queryParams.value);
  proReceiveRegisterList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  contractReceiveLeaders.value = '';
  contractLeadersName.value = '';
  contractPresidentsName.value = '';
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  proReceiveRegisterFormRef.value?.resetFields();
  // 重置合同选择器状态
  contractList.value = [];
  contractReceiveLeaders.value = '';
  contractLeadersName.value = '';
  contractPresidentsName.value = '';
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  // 重置搜索条件用户选择
  selectedSearchPresident.value = null;
  selectedSearchPresidentName.value = '';
  selectedSearchLeader.value = null;
  selectedSearchLeaderName.value = '';

  queryFormRef.value?.resetFields();

  // 重置查询参数中的新字段
  queryParams.value.conName = undefined;
  queryParams.value.proPresidentId = undefined;
  queryParams.value.proLeaderId = undefined;

  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: ProReceiveRegisterVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  form.value.registerTime = getToday();
  form.value.registerBy = Number(userStore.userId);
  dialog.visible = true;
  dialog.title = '添加回款登记';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: ProReceiveRegisterVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getProReceiveRegister(_id);
  Object.assign(form.value, res.data);

  // 回显用户名称
  if (res.data.registerName) {
    form.value.registerName = res.data.registerName;
  }

  // 通过合同ID使用分页接口查询并回显（便于带出 presidentsName/leadersName）
  if (form.value.conId) {
    try {
      const resList = await listProContract({ pageNum: 1, pageSize: 1, id: form.value.conId });
      const rows = resList?.rows || [];
      if (rows.length) {
        const contract = rows[0];
        if (!contractList.value.find((c) => c.id === contract.id)) {
          contractList.value.unshift(contract);
        }
        // 直接回显项目负责人与执行总裁
        contractLeadersName.value = contract.leadersName || '';
        contractPresidentsName.value = contract.presidentsName || '';
      }
      // 获取合同收款负责人信息
      await handleContractChange(form.value.conId);
    } catch (e) {
      // ignore
    }
  }

  dialog.visible = true;
  dialog.title = '修改回款登记';
};

/** 提交按钮 */
const submitForm = () => {
  proReceiveRegisterFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // conId 为必填
      if (!form.value.conId) {
        proxy?.$modal.msgError('请选择合同名称');
        buttonLoading.value = false;
        return;
      }
      const payload: any = { ...form.value };

      if (form.value.id) {
        await updateProReceiveRegister(payload).finally(() => (buttonLoading.value = false));
      } else {
        await addProReceiveRegister(payload).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    } else {
      proxy?.$modal.msgError('请填写所有必填项');
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: ProReceiveRegisterVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除回款登记编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delProReceiveRegister(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'pro/receive/register/export',
    {
      ...queryParams.value
    },
    `project_receive_register_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>

<style scoped>
.asterisk {
  color: #f56c6c;
  margin-right: 4px;
  font-size: 16px;
  font-family: inherit;
}

/* 合同选择器样式 */
.contract-selector-container {
  width: 100%;
}

.selected-contract {
  display: flex;
  align-items: center;
  width: 100%;
}

.selected-contract .el-input {
  flex: 1;
}

/* 只读输入框样式 */
.readonly-placeholder .el-input__inner {
  color: #c0c4cc;
  background-color: #f5f7fa;
}

.readonly-placeholder .el-input__inner::placeholder {
  color: #c0c4cc;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .selected-contract {
    flex-direction: column;
    gap: 8px;
  }

  .selected-contract .el-input {
    width: 100% !important;
  }

  .selected-contract .el-button {
    width: 100%;
    margin-left: 0 !important;
  }

  .readonly-placeholder .el-input__inner {
    font-size: 12px;
  }
}
</style>
